package leetcode.test;

import java.util.Stack;

public class ReverseLinked {


    /**
     * 反转链表一：双指针迭代
     */
    public ListNode reverseLinked2(ListNode head){
        ListNode pre = null;
        ListNode cur = head;
        ListNode tmp = null;
        while (cur != null) {
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }

    /**
     * 反转链表二：使用辅助栈
     */
    public ListNode reverseLinked1(ListNode head){
        if (head == null)
            return null;
        Stack<ListNode> stk = new Stack<>();
        while (head != null){
            stk.add(head);
            head = head.next;
        }
        ListNode pre = new ListNode(-1);
        ListNode cur = pre;
        while (!stk.isEmpty()) {
            cur.next = stk.pop();
            cur = cur.next;
        }
        cur.next = null;
        return pre.next;
    }

    /**
     * 反转链表三：递归
     */
    public ListNode reverseLinked4(ListNode head){
        // 1. 递归终止条件
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = reverseLinked4(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
}
